package com.cirkana.viewer.route;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.cirkana.CirkanaActivity;
import com.cirkana.serial.SerializationException;
import com.cirkana.viewer.R;
import com.cirkana.viewer.route.gpx.GpxTrackerParser;
import com.cirkana.viewer.route.gpx.Tracker;

public class SelectRouteActivity extends CirkanaActivity {

	public static final int REQUEST_ROUTEDETAIL = 1;

	public static final int RESULT_SELECTROUTE_OK = 0;

	private ListView localRoutesListView;
	private String[] localRoutesList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.localRoutesList = RoutesUtil.getLocalRoutes(getAssets());

		setContentView(R.layout.selectroute);

		localRoutesListView = (ListView) findViewById(R.id.routesList);
		localRoutesListView.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, localRoutesList));

		localRoutesListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				String fileName = localRoutesListView.getItemAtPosition(
						position).toString();
				Tracker tracker = null;
				try {
					tracker = GpxTrackerParser.getTracker(RoutesUtil
							.openLocalRoute(getAssets(), fileName));
				} catch (Exception e) {
					openMessageBox("Error", e.getMessage());
				}
				tracker.setFileName(fileName);

				try {
					startActivityForResult(RouteDetailActivity.createIntent(
							SelectRouteActivity.this, tracker),
							REQUEST_ROUTEDETAIL);
				} catch (SerializationException e) {
					openMessageBox("Error", e.getMessage());
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case REQUEST_ROUTEDETAIL:
			switch (resultCode) {
			case CirkanaActivity.RESULT_CANCEL:
				break;
			case RouteDetailActivity.RESULT_ROUTEDETAIL_OK:
				RouteDetailPassData d = (RouteDetailPassData) getResult();
				SelectRoutePassData r = new SelectRoutePassData();
				r.setTracker(d.getTracker());
				try {
					setResult(RESULT_SELECTROUTE_OK, r);
				} catch (SerializationException e) {
					openMessageBox("Error", e.getMessage());
				}
				finish();
				break;
			}
			break;
		}
	}

	public static Intent createIntent(Context context, Tracker tracker)
			throws SerializationException {
		Intent intent = new Intent(context, SelectRouteActivity.class);
		SelectRoutePassData data = new SelectRoutePassData();
		data.setTracker(tracker);
		setPassData(intent, data);
		return intent;
	}
}
